package dblayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import modellayer.CompanyType;
import modellayer.KeyPerson;

public class CompanyTypeDB
{
	private Connection con;
	
	public CompanyTypeDB()
	{
		con = DBConnection.getInstance().getDBcon();
	}
	
	public CompanyType findCompanyTypeById(int id)
	{
		String wClause = " id='"+id+"' ";
		
		return singleWhere(wClause);
	}
	
	private CompanyType singleWhere(String wClause)
	{
		ResultSet results;
		CompanyType companyTypeObj = null;
		
		String query = buildQuery(wClause);
		
		try
		{
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);
			
			if (results.next())
			{
				companyTypeObj = buildCompanyType(results);
			}
			else
			{
				companyTypeObj = null;
			}
		}
		catch (Exception e)
		{
			System.out.println("SQL query: " +query);
			System.out.println("Error: " +e);
		}
		
		return companyTypeObj;
	}
	
	private String buildQuery(String wClause)
	{
		String query = "SELECT id, name FROM sem2_CompanyType";
		
		if (!wClause.isEmpty())
		{
			query += " WHERE " +wClause;
		}
		
		return query;
	}
	
	private CompanyType buildCompanyType(ResultSet results)
	{
		CompanyType companyTypeObj = null;
		
		try
		{
			companyTypeObj = new CompanyType(results.getInt("id"), results.getString("name"));
		}
		catch (SQLException e)
		{
			System.out.println("Error building CompanyType object! \n Error: " +e);
		}
		
		return companyTypeObj;
	}
	
	public ArrayList<CompanyType> listAllTypes()
	{
		String query = "SELECT sem2_CompanyType.* FROM sem2_CompanyType";
		
		return miscWhere(query);
	}
	
	private ArrayList<CompanyType> miscWhere(String query)
	{
		ArrayList<CompanyType> tList = new ArrayList<CompanyType>();
		ResultSet results;
		
		try
		{
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);
			
			while (results.next())
			{
				tList.add(buildCompanyType(results));
			}
		}
		catch (Exception e)
		{
			System.out.println("SQL query TypeDB: "+query);
			System.out.println("	error: "+e);
		}
		
		return tList;
	}
}
